<template>
  <div class="commonBoxmp">
    <TableV2
      class="flex1"
      :apiFunction="listRole"
       :isInit="false"
        :filter="{
        }"
      ref="tableV2Ref"
      :columns="state.columnData"
    >
      <template #tableHeader>
        <div class="jcb aic w100">
          <el-button type="primary" @click="handleAddUser">添加角色</el-button>
        </div>
      </template>
      <template #operation>
        <el-table-column label="操作" fixed="right" width="160px" align="left">
          <template #default="scope">
            <div class="aic">
   <el-link type="primary" @click="handleUpdate(scope.row)"
              >修改</el-link
            >
            <el-link type="primary" class="mx5" @click="handleDelete(scope.row)"
              >删除</el-link
            >
            <el-dropdown @command="handleMoreTool($event, scope.row)">
              <el-link class="ml10" type="primary">
                更多
                <el-icon class="el-icon--right"> <arrow-down /> </el-icon
              ></el-link>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleDataScope"
                    >数据权限</el-dropdown-item
                  >
                  <el-dropdown-item command="handleAuthUser"
                    >分配用户</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            </div>
         
          </template>
        </el-table-column>
      </template>
    </TableV2>

    <el-dialog
      v-model="state.userVisible"
      :title="state.title"
      width="50%"
      destroy-on-close
      center
    >
      <el-form
        ref="ruleFormRef"
        :model="state.form"
        :rules="state.rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="state.form.roleName"
                placeholder="请输入角色名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="roleKey">
              <template #label>
                <div class="aic">
                  <el-tooltip
                    content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                    placement="top"
                  >
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                  权限字符
                </div>
              </template>
              <el-input
                v-model="state.form.roleKey"
                placeholder="请输入权限字符"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色顺序" prop="roleSort">
              <el-input-number
                v-model="state.form.roleSort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <selectDict
                class="w100"
                dataType="radio"
                dictCode="sys_normal_disable"
                v-model="state.form.status"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="菜单权限" prop="roleSort">
              <div>
                <div>
                  <el-checkbox
                    v-model="state.menuExpand"
                    @change="handleCheckedTreeExpand($event, 'menu')"
                    >展开/折叠</el-checkbox
                  >
                  <el-checkbox
                    v-model="state.menuNodeAll"
                    @change="handleCheckedTreeNodeAll($event, 'menu')"
                    >全选/全不选</el-checkbox
                  >
                  <el-checkbox
                    v-model="state.form.menuCheckStrictly"
                    @change="handleCheckedTreeConnect($event, 'menu')"
                    >父子联动</el-checkbox
                  >
                </div>
                <el-tree
                  class="tree-border"
                  :data="state.menuOptions"
                  show-checkbox
                  ref="treeRef"
                  node-key="id"
                  :check-strictly="!state.form.menuCheckStrictly"
                  empty-text="加载中，请稍候"
                  :props="state.defaultProps"
                ></el-tree>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="state.form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.userVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog
      :title="state.title"
      v-model="state.openDataScope"
      width="500px"
      append-to-body
    >
      <el-form :model="state.form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="state.form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="state.form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select
            v-model="state.form.dataScope"
            @change="dataScopeSelectChange"
          >
            <el-option
              v-for="item in state.dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="state.form.dataScope == 2">
          <el-checkbox
            v-model="state.deptExpand"
            @change="handleCheckedTreeExpand($event, 'dept')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="state.deptNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'dept')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="state.form.deptCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'dept')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="state.deptOptions"
            show-checkbox
            default-expand-all
            ref="deptRef"
            node-key="id"
            :check-strictly="!state.form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="state.defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="state.openDataScope = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <addOrEdit v-model="drawerEditAdd" :id="roleId" @update="getList"/>
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, getCurrentInstance, onMounted, nextTick, shallowRef } from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "/@ts/components/table/Column";
import selectDict from "/@/components/selectDict/index.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import formatTool from "/@ts/hooks/format";
import DictTag from "/@/components/DictTag/index.vue";
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  changeRoleStatus,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/role";
import addOrEdit from './component/addOrEdit.vue'
import { baseSchema } from "/@ts/defaultValue/detail";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "/@ts/axios/urlApi/system/menu";
import { routerPush } from "/@ts/hooks/route";
const router = useRouter();
const route = useRoute();
const roleId = shallowRef("")
const { parseTime, addDateRange, getDict } = formatTool();
const drawerEditAdd= shallowRef(false)
let dict: any = reactive({
  sys_job_status: [],
});
onMounted(async () => {
  dict.sys_job_status = await getDict("sys_job_status");
});

 
const state: any = reactive({
  openDataScope: false,
  defaultProps: {
    children: "children",
    label: "label",
  },
  menuOptions: [],
  deptOptions: [],
  dataScopeOptions: [
    {
      value: "1",
      label: "全部数据权限",
    },
    {
      value: "2",
      label: "自定数据权限",
    },
    {
      value: "3",
      label: "本部门数据权限",
    },
    {
      value: "4",
      label: "本部门及以下数据权限",
    },
    {
      value: "5",
      label: "仅本人数据权限",
    },
  ],
  deptExpand: false,
  deptNodeAll: false,
  menuExpand: false,
  menuNodeAll: false,
  // 表格基础配置 start
  title: "",
  form: {},
  userVisible: false,
  rules: {
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [
      { required: true, message: "角色顺序不能为空", trigger: "blur" },
    ],
  },
  dateRange: [], //时间范围筛选

  height: 0,
  tableData: [],
  columnData: [
    {
      label: "角色编号",
      prop: "roleId",
      visible: true,
    },
    {
      label: "角色名称",
      prop: "roleName",
      visible: true,
    },
    {
      label: "权限字符",
      prop: "roleKey",
      visible: true,
    },

    {
      label: "显示顺序",
      prop: "roleSort",
      visible: true,
    },
    {
      label: "状态",
      prop: "status",
      visible: true,
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_job_status}
            onClick={() => handleStatusChange(row)}
          ></DictTag>
        );
      },
    },
     ...(baseSchema.filter(res=>res.prop=='createdTime'))
  ],
  loading: false,
  // 表格基础配置 end
});

// 所有菜单节点数据
const getMenuAllCheckedKeys = () => {
  // 目前被选中的菜单节点
  let checkedKeys = treeRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
};
// 所有部门节点数据
const getDeptAllCheckedKeys = () => {
  // 目前被选中的菜单节点
  let checkedKeys = deptRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
};
const submitDataScope = (formEl: FormInstance | undefined) => {
  if (state.form.roleId != undefined) {
    if(state.form.dataScope == 2){
       state.form.deptIds = getDeptAllCheckedKeys();
    }else {
      state.form.deptIds =[]
    }
   
    dataScope(state.form).then((response: any) => {
      state.openDataScope = false;
      getList();
    });
  }
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  state.form.menuIds = getMenuAllCheckedKeys();
  if (state.form.roleId != undefined) {
    updateRole(state.form).then((response: ResponseConfig) => {
      ElMessage.success("修改成功");
      state.userVisible = false;
      getList();
    });
  } else {
    addRole(state.form).then((response: ResponseConfig) => {
      ElMessage.success("新增成功");
      state.userVisible = false;
      getList();
    });
  }
};
const handleDelete = (row: any) => {
  const roleIds = row.roleId;
  ElMessageBox.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
    .then(function () {
      return delRole(roleIds);
    })
    .then(() => {
      ElMessage.success("删除成功");
      getList();
    })
    .catch(function () {});
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  roleId.value = row.roleId;
  drawerEditAdd.value=true
  // const roleMenu = getRoleMenuTreeselect(roleId);
  // getRole(roleId).then((response: ResponseConfig) => {
  //   state.title = "修改角色";
  //   state.form = response.data;
  //   nextTick(() => {
  //     roleMenu.then((res: ResponseConfig) => {
  //       let checkedKeys = res.checkedKeys;
  //       checkedKeys.forEach((v: string) => {
  //         nextTick(() => {
  //           treeRef.value.setChecked(v, true, false);
  //         });
  //       });
  //     });
  //   });
  //   state.userVisible = true;
  // });
};
const handleAddUser = () => {
  roleId.value =""
  getMenuTreeselect();
  drawerEditAdd.value = true;

};
// 表格基础配置 end
//查询用户列表
const tableV2Ref = ref()
const getList = () => {
 tableV2Ref.value.getList()
};
const ruleFormRef = ref<FormInstance>();

const treeRef = ref<any>();
const deptRef = ref<any>();
const handleDataScope = (row: any) => {
  state.form = {};
  const deptTreeSelect = getDeptTree(row.roleId);
  getRole(row.roleId).then((response: ResponseConfig) => {
    state.form = response.data;
    state.openDataScope = true;
    nextTick(() => {
      deptTreeSelect.then((res: ResponseConfig) => {
        deptRef.value.setCheckedKeys(res.checkedKeys);
      });
    });
    state.title = "分配数据权限";
  });
};
const handleAuthUser = (row: any) => {
  const roleId = row.roleId;
  routerPush("/system/role-auth/user/" + roleId);
};
//更多操作
const handleMoreTool = (val: string, row: any) => {
  switch (val) {
    case "handleDataScope":
      handleDataScope(row);
      break;

    case "handleAuthUser":
      handleAuthUser(row);
      break;
  }
};
/** 查询菜单树结构 */
const getMenuTreeselect = () => {
  menuTreeselect().then((response: any) => {
    state.menuOptions = response.data;
  });
};
/** 根据角色ID查询菜单树结构 */
const getRoleMenuTreeselect = (roleId?: string): Promise<ResponseConfig> => {
  return roleMenuTreeselect(roleId).then((response: ResponseConfig) => {
    state.menuOptions = response.menus;
    return response;
  });
};
/** 根据角色ID查询部门树结构 */
const getDeptTree = (roleId?: string) => {
  return deptTreeSelect(roleId).then((response: ResponseConfig) => {
    state.deptOptions = response.depts;
    return response;
  });
};
// 角色状态修改
const handleStatusChange = (row?: any) => {
  let text = row.status === "0" ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      ElMessage.success(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
};
// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: any, type: any) => {
  if (type == "menu") {
    let treeList = state.menuOptions;
    for (let i = 0; i < treeList.length; i++) {
      treeRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == "dept") {
    let treeList = state.deptOptions;
    for (let i = 0; i < treeList.length; i++) {
      deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
};
// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: any) => {
  if (type == "menu") {
    treeRef.value.setCheckedNodes(value ? state.menuOptions : []);
  } else if (type == "dept") {
    deptRef.value.setCheckedNodes(value ? state.deptOptions : []);
  }
};
// 树权限（父子联动）
const handleCheckedTreeConnect = (value: any, type: any) => {
  if (type == "menu") {
    state.form.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    state.form.deptCheckStrictly = value ? true : false;
  }
};
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss"></style>
